package com.kehutong.auth.action;

import com.kehutong.auth.entity.Account;
import com.kehutong.auth.enums.AccountStatus;
import com.kehutong.common.DoveClient;
import com.kehutong.common.util.Token;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;

/**
 * 账号
 * @author: liukunlong
 * @date: 2021-04-17 14:28
 */
@MvcAction
@ReqMapping("/kht-bin/account")
public class AccountAction {

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private DoveClient doveClient;

    @ReqMapping("/list")
    public Object list(Token token, JSONObject jsonObject) {
        Page<Account> page = jdbcSession.findPage(Account.class)
                .eq("deleted", false)
                .eq(jsonObject, "id")
                .page(jsonObject)
                .exe();
        return page;
    }


    @ReqMapping("/get")
    public Object get(Token token,Account item) {
        return item;
    }

    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    public Object save(Account item) throws Exception {
        jdbcSession.insert(item);
        return Result.success(item);
    }

    @Bean(copy = true)
    public Object update(Account item) throws Exception {
        jdbcSession.updateById(item);
        return Result.success(item);
    }

    @ReqMapping("/delete")
    public Object delete(Account item) throws Exception {
        if (Objects.nonNull(item)) {
            item.setStatus(AccountStatus.CANCEL);
            jdbcSession.updateById(item);
        }
        return Result.success();
    }

    @ReqMapping("/checkAttention")
    public Object checkAttention(Token token,String appId) throws Exception{
        if (Objects.isNull(token)) {
            return Result.unlogin();
        }
        if (Objects.isEmpty(appId)) {
            return Result.error(0,"appId不能为空");
        }
        JSONObject rs = doveClient.post("/kht-bin/wechat/getMemberMap", http -> {
            http.addParam("mn_app_id",appId);
            http.addParam("khtId",token.getUuid());
        });
        int code = rs.getIntValue("code");
        if (code != 200) {
            return Result.error(code, rs.getString("message"));
        }
        JSONObject memberMap = rs.getJSONObject("data");
        if(Objects.isEmpty(memberMap)){
            return Result.error(0,"没有绑定账号数据");
        }
        String mpOpenId=memberMap.getString("mp_open_id");
        if(Objects.isEmpty(mpOpenId)){
            return Result.success(false);
        }else{
            return Result.success(true);
        }
    }




}
